# -*- coding: utf-8 -*-
# File : student_services.py
# Author: taoyahui
# Date : 2021/4/7

from student.models import *
from django.core.paginator import Paginator
from django.core import serializers
from student.results import *
from student import utils


# 分页查询学生信息
def query_student(query_dic={}):
    # 页数查询的默认值为1
    query_page = 1
    # 判断request的body信息中是否包含page字段
    if query_dic['page'] is not None:
        query_page = query_dic['page']  # 获取request传入内容，如果没有则设置默认值1
    # 判断request的content字段不为空，并且有内容
    if query_dic['content'] is not None and len(query_dic['content']) > 0 :
        objects = stu_info.objects.filter(stu_name=query_dic['content'])    # 如果传入request有content内容则按学生姓名查询
    else:
        # 如果不满足以上条件，默认查询所有学生信息
        objects = stu_info.objects.all()
    # 将查询的数据进行分页，每页10条数据
    p = Paginator(objects, 10)
    # 获取当前页的数据
    current_p = p.page(query_page)
    object_list = current_p.object_list
    # 将查询的数据转化为json格式
    json_data = serializers.serialize('json', object_list)
    # 拼接返回内容
    dict = {
        'list': json.loads(json_data),
        'has_next': current_p.has_next()
    }
    # 生成返回内容
    return_content = {
        'code': 200,
        'data': dict
    }
    return json.dumps(return_content)


# 插入学生信息
def insert_student(dict):
    # 判断request的body中是否有stu_num和stu_name
    if not utils.has_keys(dict, 'stu_num', 'stu_name'):
        return info_incomplete_result
    # 插入学生的学号已存在，则返回信息已存在错误信息
    if stu_info.objects.filter(stu_num=dict['stu_num']).count() > 0:
        # 返回信息已存在通用结果
        return info_exists_result
    # 使用Django的models功能插入数据
    student = stu_info(stu_num=dict['stu_num'],
                       stu_name=dict['stu_name'],
                       stu_birth=dict['stu_birth'],
                       stu_add=dict['stu_add'])
    student.save()
    return success_result


# 更新学生信息
def update_student(dict):
    # 如果输入内容中没有id，则返回信息输入错误信息
    if not utils.has_keys(dict, 'id'):
        return info_incomplete_result
    try:
        # 通过request的body id查询学生信息
        student = stu_info.objects.get(id=dict['id'])
        # 更新学生学号
        if 'stu_num' in dict.keys():
            student.stu_num = dict['stu_num']
        # 更新学生姓名
        if 'stu_name' in dict.keys():
            student.stu_name = dict['stu_name']
        # 更新学生生日
        if 'stu_birth' in dict.keys():
            student.stu_birth = dict['stu_birth']
        # 更新学生地址
        if 'stu_add' in dict.keys():
            student.stu_add = dict['stu_add']
        # 保存更新内容
        student.save()
        return success_result
    except Exception as e:
        return error_result


# 删除学生信息
def remove_student(id):
    # 判断请求是否有输入学生学号信息，若没有保存
    if not id:
        return info_error_result
    # 通过id获取学生信息
    student = stu_info.objects.get(id=id)
    # 删除学生信息
    student.delete()
    return success_result
